/*
 * @Author: jingfuu@163.com
 * @Date: 2024-09-09 14:23:10
 * @LastEditTime: 2024-12-07 17:47:48
 * @Description: 应用根模块
 */
import {
  MiddlewareConsumer,
  Module,
  RequestMethod,
  ValidationPipe,
} from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { CommonModule } from './common/common.module';
import { LoggerMiddleware } from './common/middleware/logger.middleware';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
import { HttpExceptionFilter } from './common/exception-filter/HttpExceptionFilter';
import { LoggingInterceptor } from './common/interceptor/LoggingInterceptor';
import { SystemModule } from './system/system.module';
import { DefaultExceptionsFilter } from './common/exception-filter/DefaultExceptionFilter';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';
import { ClsModule } from 'nestjs-cls';
import { BadRequestExceptionFilter } from './common/exception-filter/BadRequestExceptionFilter';
import { AuthGuard } from './common/guard/auth.guard';
import { RolesGuard } from './common/guard/roles.guard';
import { PreAuthorizeGuard } from './common/guard/pre-authorize.guard';
import { Constants } from './common/Constants';
import { EventEmitterModule } from '@nestjs/event-emitter';

@Module({
  imports: [
    EventEmitterModule.forRoot(),
    ClsModule.forRoot({
      middleware: {
        mount: true,
        setup: (cls, req) => {
          const [type, token] = req.headers.authorization?.split(' ') ?? [];
          cls.set(Constants.USER_TOKEN, type === 'Bearer' ? token : undefined);
        },
      },
      global: true,
    }),
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', 'static'),
      serveRoot: '/static',
      // renderPath: 'index', 响应默认html的访问前缀，如果rootPath下放了spa应用，默认static下访问任何目录，都是返回spa应用首页inde.html，除非你指定了renderPath，这里只有访问 /statis/ 和 /statis/index 才返回spa应用首页inde.html
    }),
    // 加载不同环境配置文件
    ConfigModule.forRoot({
      envFilePath: [
        '.env.default',
        process.env.NODE_ENV === 'production'
          ? '.env.prod'
          : process.env.NODE_ENV == 'development'
            ? '.env.development'
            : '.env.test',
      ],
      isGlobal: true,
    }),
    //系统模块，用户、部门、角色、菜单等接口服务
    SystemModule,
    //系统公共模块
    CommonModule,
  ],
  providers: [
    //声明全局异常拦截器
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter,
    },
    {
      provide: APP_FILTER,
      useClass: DefaultExceptionsFilter,
    },
    {
      provide: APP_FILTER,
      useClass: BadRequestExceptionFilter,
    },
    {
      //公共bean校验
      provide: APP_PIPE,
      useFactory: () => {
        return new ValidationPipe({
          transform: true,
          transformOptions: {
            enableImplicitConversion: true, // 启用隐式转换
          },
        });
      },
    },
    //日志切面
    {
      provide: APP_INTERCEPTOR,
      useClass: LoggingInterceptor,
    },
    {
      provide: APP_GUARD,
      useClass: AuthGuard,
    },
    {
      provide: APP_GUARD,
      useClass: RolesGuard,
    },
    {
      provide: APP_GUARD,
      useClass: PreAuthorizeGuard,
    },
  ],
})
export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes({ path: '/**', method: RequestMethod.ALL });
  }
}
